'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import styles from './email-login.module.css';

// 工具函数
const setToken = (token: string, userData?: any) => {
  localStorage.setItem('userToken', token);
  if (userData) {
    localStorage.setItem('userData', JSON.stringify(userData));
  }
};

interface EmailLoginFormData {
  email: string;
  code: string;
  newPassword: string;
  confirmPassword: string;
}

const EmailLogin = () => {
  const router = useRouter();
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [email, setEmail] = useState('');
  const [token, setResetToken] = useState('');
  const [sliderValue, setSliderValue] = useState(0);
  const [countdown, setCountdown] = useState(0);
  const [formData, setFormData] = useState<EmailLoginFormData>({
    email: '',
    code: '',
    newPassword: '',
    confirmPassword: ''
  });
  const [message, setMessage] = useState({ type: '', content: '' });
  const [isSuccessModalVisible, setIsSuccessModalVisible] = useState(false);

  // 显示消息
  const showMessage = (type: 'success' | 'error' | 'info', content: string) => {
    setMessage({ type, content });
    setTimeout(() => setMessage({ type: '', content: '' }), 3000);
  };

  // 倒计时效果
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (countdown > 0) {
      timer = setInterval(() => {
        setCountdown(prev => prev - 1);
      }, 1000);
    }
    return () => clearInterval(timer);
  }, [countdown]);

  const handleSendCode = async () => {
    if (!formData.email || !/^\S+@\S+\.\S+$/.test(formData.email)) {
      showMessage('error', '请输入正确的邮箱地址');
      return;
    }

    try {
      setLoading(true);
      const response = await fetch('http://127.0.0.1:8000/api/forget/send-code', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email: formData.email })
      });
      
      const data = await response.json();
      
      if (data.code === 200) {
        showMessage('success', `${data.message}，验证码有效期5分钟`);
        setEmail(formData.email);
        setCurrentStep(1);
        setCountdown(60);
      } else {
        showMessage('error', data.message);
      }
    } catch (error) {
      showMessage('error', '发送验证码失败，请稍后再试');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyCode = async () => {
    if (!formData.code || !/^\d{6}$/.test(formData.code)) {
      showMessage('error', '请输入6位数字验证码');
      return;
    }

    try {
      setLoading(true);
      const response = await fetch('http://127.0.0.1:8000/api/forget/verify-code', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email,
          code: formData.code
        })
      });
      
      const data = await response.json();
      
      if (data.code === 200) {
        showMessage('success', '验证成功');
        setResetToken(data.data.token);
        setCurrentStep(2);
      } else {
        showMessage('error', data.message);
      }
    } catch (error) {
      showMessage('error', '验证失败，请稍后再试');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleResetPassword = async () => {
    if (sliderValue !== 100) {
      showMessage('error', '请先完成滑块验证');
      return;
    }

    if (!formData.newPassword || formData.newPassword.length < 6) {
      showMessage('error', '密码至少6位');
      return;
    }

    if (formData.newPassword !== formData.confirmPassword) {
      showMessage('error', '两次输入密码不一致');
      return;
    }

    try {
      setLoading(true);
      const response = await fetch('http://127.0.0.1:8000/api/forget/reset-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          token,
          newPassword: formData.newPassword,
          sliderValue
        })
      });
      
      const data = await response.json();
      
      if (data.code === 200) {
        setIsSuccessModalVisible(true);
      } else {
        showMessage('error', data.message);
      }
    } catch (error) {
      showMessage('error', '重置密码失败，请稍后再试');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleBackToLogin = () => {
    setIsSuccessModalVisible(false);
    router.push('/login');
  };

  const handleInputChange = (field: keyof EmailLoginFormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSliderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSliderValue(parseInt(e.target.value));
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return (
          <div className={styles.stepContent}>
            <h3 className={styles.stepTitle}>验证邮箱</h3>
            <p className={styles.stepDescription}>请输入您的注册邮箱地址</p>
            
            <div className={styles.inputWrapper}>
              <Image src="/img/email.svg" alt="邮箱" width={20} height={20} className={styles.inputIconImg} />
              <input
                type="email"
                placeholder="请输入注册邮箱"
                className={styles.mobileInput}
                value={formData.email}
                onChange={(e) => handleInputChange('email', e.target.value)}
                required
              />
            </div>
            
            <button 
              className={styles.mobileLoginBtn}
              onClick={handleSendCode}
              disabled={loading || countdown > 0}
            >
              {countdown > 0 ? `${countdown}秒后重新获取` : (loading ? '发送中...' : '获取验证码')}
            </button>
          </div>
        );
      
      case 1:
        return (
          <div className={styles.stepContent}>
            <h3 className={styles.stepTitle}>输入验证码</h3>
            <p className={styles.stepDescription}>验证码已发送至 {email}</p>
            
            <div className={styles.inputWrapper}>
              <Image src="/img/code.svg" alt="验证码" width={20} height={20} className={styles.inputIconImg} />
              <input
                type="text"
                placeholder="请输入6位验证码"
                className={styles.mobileInput}
                value={formData.code}
                onChange={(e) => handleInputChange('code', e.target.value)}
                maxLength={6}
                required
              />
            </div>
            
            <div className={styles.buttonGroup}>
              <button 
                className={styles.backBtn}
                onClick={() => setCurrentStep(0)}
              >
                返回
              </button>
              <button 
                className={styles.mobileLoginBtn}
                onClick={handleVerifyCode}
                disabled={loading}
              >
                {loading ? '验证中...' : '验证'}
              </button>
            </div>
          </div>
        );
      
      case 2:
        return (
          <div className={styles.stepContent}>
            <h3 className={styles.stepTitle}>重置密码</h3>
            <p className={styles.stepDescription}>请设置您的新密码</p>
            
            <div className={styles.inputWrapper}>
              <Image src="/img/2.png" alt="密码" width={20} height={20} className={styles.inputIconImg} />
              <input
                type="password"
                placeholder="请输入6-20位新密码"
                className={styles.mobileInput}
                value={formData.newPassword}
                onChange={(e) => handleInputChange('newPassword', e.target.value)}
                required
              />
            </div>
            
            <div className={styles.inputWrapper}>
              <Image src="/img/2.png" alt="确认密码" width={20} height={20} className={styles.inputIconImg} />
              <input
                type="password"
                placeholder="请再次输入新密码"
                className={styles.mobileInput}
                value={formData.confirmPassword}
                onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
                required
              />
            </div>
            
            <div className={styles.sliderContainer}>
              <p className={styles.sliderLabel}>
                请滑动滑块完成验证: {sliderValue === 100 ? '已完成' : `${sliderValue}%`}
              </p>
              <input
                type="range"
                min="0"
                max="100"
                value={sliderValue}
                onChange={handleSliderChange}
                className={styles.slider}
              />
            </div>
            
            <button 
              className={styles.mobileLoginBtn}
              onClick={handleResetPassword}
              disabled={loading || sliderValue !== 100}
            >
              {loading ? '重置中...' : '确认重置密码'}
            </button>
          </div>
        );
      
      default:
        return null;
    }
  };

  return (
    <div className={styles.mobileLoginContainer}>
      {/* 消息提示 */}
      {message.content && (
        <div className={`${styles.message} ${styles[message.type]}`}>
          {message.content}
        </div>
      )}

      {/* 背景图片和遮罩层 */}
      <div className={styles.backgroundLayer}>
        <Image 
          src="/img/1.png" 
          alt="background" 
          fill
          className={styles.backgroundImage}
          priority
        />
        <div className={styles.backgroundOverlay}></div>
      </div>
      
      {/* 主要内容 */}
      <div className={styles.mobileContent}>
        <div className={styles.mobileHeader}>
          <h1 className={styles.appTitle}>邮箱登录</h1>
          <p className={styles.appSubtitle}>通过邮箱验证重置密码</p>
        </div>

        {/* 步骤指示器 */}
        <div className={styles.stepsContainer}>
          <div className={styles.steps}>
            {['验证', '输入', '重置'].map((step, index) => (
              <div key={index} className={`${styles.step} ${currentStep >= index ? styles.stepActive : ''}`}>
                <div className={styles.stepNumber}>{index + 1}</div>
                <span className={styles.stepText}>{step}</span>
              </div>
            ))}
          </div>
        </div>

        <div className={styles.mobileFormContainer}>
          {renderStepContent()}
        </div>
        
        <div className={styles.mobileFooter}>
          <p>想起来密码了？
            <span 
              className={styles.linkText}
              onClick={() => router.push('/login')}
            >
              去登录
            </span>
          </p>
          <p>还没有账号？
            <span 
              className={styles.linkText}
              onClick={() => router.push('/register')}
            >
              立即注册
            </span>
          </p>
          <p>© 2020 HTTPS://MMOO.FUN MMO设计</p>
        </div>
      </div>

      {/* 成功弹窗 */}
      {isSuccessModalVisible && (
        <div className={styles.modal}>
          <div className={styles.modalContent}>
            <div className={styles.modalHeader}>
              <h3>密码重置成功</h3>
            </div>
            <div className={styles.modalBody}>
              <p>您的密码已成功重置！</p>
              <p>请使用新密码登录系统。</p>
              <button 
                className={styles.mobileLoginBtn}
                onClick={handleBackToLogin}
              >
                前往登录
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default EmailLogin;